import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import '../dialog/loading.dart';

///需要加载的内容类型
enum WebViewType {
  //html文本
  HTMLTEXT,
  //链接
  URL
}

///定义js通信回调方法
typedef dynamic JsChannelCallback(List<dynamic> arguments);

///封装的WebView组件
class WebViewWidget extends StatefulWidget {
  const WebViewWidget({
    super.key,
    required this.webViewType,
    required this.loadResource,
    this.headers,
    this.jsChannelMap,
    this.onWebViewCreated,
    this.onBeforeLoad,
    this.clearCache,
    this.autoLoad = true, // 是否自动加载
    this.onRpcMessage, // JRPC 消息回调
  });

  //需要加载的内容类型
  final WebViewType webViewType;

  //给webview加载的数据,可以是url，也可以是html文本
  final String loadResource;

  // 新增：请求头
  final Map<String, String>? headers;

  //是否清除缓存后再加载
  final bool? clearCache;

  // 是否自动加载资源
  final bool autoLoad;

  //与js通信的channel集合
  final Map<String, JsChannelCallback>? jsChannelMap;

  final Function(InAppWebViewController controller)? onWebViewCreated;

  final Future<void> Function(InAppWebViewController controller)? onBeforeLoad;

  /// JRPC 消息回调（由 WebView 内部注册 RpcFromJS handler 调用）
  final void Function(String payload)? onRpcMessage;

  @override
  State<StatefulWidget> createState() {
    return _WebViewWidgetState();
  }
}

class _WebViewWidgetState extends State<WebViewWidget> {
  //webview控制器
  late InAppWebViewController webViewController;
  final GlobalKey webViewKey = GlobalKey();

  // webview配置
  InAppWebViewSettings settings = InAppWebViewSettings(
    // 跨平台配置
    useShouldOverrideUrlLoading: true,
    mediaPlaybackRequiresUserGesture: false,
    // android平台配置
    //不允许缩放
    builtInZoomControls: false,
    //支持HybridComposition
    useHybridComposition: true,
    // ios平台配置
    allowsInlineMediaPlayback: true,
  );

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return InAppWebView(
        key: webViewKey,
        initialSettings: settings,
        onWebViewCreated: (controller) async {
          //webview初始化完成之后加载数据
          webViewController = controller;

          //是否清除缓存后再加载
          if (widget.clearCache == true) {
            InAppWebViewController.clearAllCache();
          }

          // 如果需要预处理，先执行
          if (widget.onBeforeLoad != null) {
            await widget.onBeforeLoad!(controller);
          }

          // 自动加载资源
          if (widget.autoLoad) {
            if (widget.webViewType == WebViewType.HTMLTEXT) {
              webViewController.loadData(data: widget.loadResource);
            } else if (widget.webViewType == WebViewType.URL) {
              webViewController.loadUrl(
                  urlRequest: URLRequest(url: WebUri(widget.loadResource)));
            }
          }

          // 回调给上层
          widget.onWebViewCreated?.call(controller);

          // 注册默认的 JRPC 通道
          controller.addJavaScriptHandler(
            handlerName: 'RpcFromJS',
            callback: (args) {
              if (args.isNotEmpty) {
                final payload = args.first as String;
                log("收到 Js JRpc 消息:$payload");

                widget.onRpcMessage?.call(payload); // 交给上层处理
                return payload;
              }
              return null;
            },
          );

          // 保留扩展点：注册与js通信回调
          widget.jsChannelMap?.forEach((handlerName, callback) {
            webViewController.addJavaScriptHandler(
                handlerName: handlerName, callback: callback);
          });
        },

        // 拦截所有跳转，重新加上 headers
        shouldOverrideUrlLoading: (controller, navigationAction) async {
          final uri = navigationAction.request.url;
          if (uri != null) {
            controller.loadUrl(
              urlRequest: URLRequest(
                url: uri,
                headers: widget.headers ?? {},
              ),
            );
            return NavigationActionPolicy.CANCEL; // 阻止默认跳转
          }
          return NavigationActionPolicy.ALLOW;
        },

        onConsoleMessage: (controller, consoleMessage) {
          log("consoleMessage ====来自于js的打印==== \n $consoleMessage");
        },
        onProgressChanged: (InAppWebViewController controller, int progress) {},
        onLoadStart: (InAppWebViewController controller, Uri? url) {
          Loading.showLoading(duration: const Duration(seconds: 45));
        },
        onReceivedHttpError: (InAppWebViewController controller,
            WebResourceRequest request, WebResourceResponse response) {
          Loading.dismissAll();
        },
        onLoadStop: (InAppWebViewController controller, Uri? url) {
          Loading.dismissAll();
        },
        onPageCommitVisible: (InAppWebViewController controller, Uri? url) {});
  }
}
